import { PlusOutlined } from '@ant-design/icons';
import type { ActionType } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { Button, Card, Space } from 'antd';
import { useRef, useState } from 'react';
import CommonDrawer from '../CommonDrawer';
import CommonForm, { type CommonFormRef } from '../CommonForm';
import SearchForm from '../SearchForm';
import SmartBreadcrumb from '../SmartBreadcrumb';
import { buildActionColumn, t } from '../utils/index';
import { usePageTemplateActions, usePageTemplateData, usePageTemplateForm } from './hooks';
import './index.less';
import type { PageTemplateProps } from './types';

function PageTemplate<T extends Record<string, any>>({
  pageConfig,
  searchConfig,
  tableConfig,
  formConfig,
  actionConfig,
  batchActionConfig,
  crudConfig,
}: PageTemplateProps<T>) {
  // 解构配置
  const { breadcrumb, isShowBreadcrumb = true } = pageConfig || {};
  const { columns, rowKey = 'id', props: tableProps } = tableConfig;
  const { fields: searchFields, initialValues: searchInitialValues, onSearch, onReset } = searchConfig || {};
  const {
    fields: formFields,
    sections: formSections,
    initialValues: formInitialValues,
    onSubmit: onFormSubmit,
    onCancel: onFormCancel,
  } = formConfig || {};
  const {
    permissions = { create: true, update: true, delete: true, view: true },
    customActions,
    onAction,
  } = actionConfig || {};
  const { enabled, renderCustom: renderBatchActions } = batchActionConfig || {};

  // Refs
  const actionRef = useRef<ActionType>();
  const formRef = useRef<CommonFormRef>(null);

  // 批量选择状态
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [selectedRows, setSelectedRows] = useState<T[]>([]);

  // 数据加载 Hook
  const {
    loading,
    crudService,
    loadData,
    handleSearch: onSearchHandler,
    handleReset: onResetHandler,
  } = usePageTemplateData<T>(crudConfig, searchFields, searchInitialValues, onSearch, onReset);

  // 表单管理 Hook
  const {
    formVisible,
    formMode,
    handleFormOpen,
    handleFormSubmit: onFormSubmitHandler,
    handleFormCancel,
  } = usePageTemplateForm<T>(rowKey, formRef, crudService, onFormSubmit, onFormCancel);

  // 操作管理 Hook
  const { handleAction } = usePageTemplateActions<T>(rowKey, crudService, handleFormOpen, customActions, onAction);

  // 合并列配置
  const finalColumns = [
    ...columns,
    ...(permissions.view || permissions.update || permissions.delete || customActions
      ? [buildActionColumn(permissions, (type, record) => handleAction(type, record, actionRef), customActions)]
      : []),
  ];

  // 表单标题和按钮文本
  const formTitleMap = {
    create: t('common', 'create'),
    edit: t('common', 'edit'),
    view: t('common', 'view'),
  };
  const confirmTextMap = {
    create: t('common', 'create'),
    edit: t('common', 'edit'),
    view: t('common', 'view'),
  };

  return (
    <div className="page-template">
      <Card className="page-template-header-card">
        {isShowBreadcrumb && (
          <div className="page-template-breadcrumb">
            <SmartBreadcrumb customItems={breadcrumb?.items} />
          </div>
        )}
        {searchFields && searchFields.length > 0 && (
          <div className="page-template-search-section">
            <SearchForm
              fields={searchFields}
              initialValues={searchInitialValues}
              onSearch={(values) => onSearchHandler(values, actionRef)}
              onReset={() => onResetHandler(actionRef)}
            />
          </div>
        )}
      </Card>

      <Card className="page-template-table-card">
        <ProTable<T>
          actionRef={actionRef}
          columns={finalColumns}
          request={loadData}
          rowKey={rowKey}
          search={false}
          dateFormatter="string"
          headerTitle={
            <Space>
              {permissions.create && (
                <Button
                  type="primary"
                  icon={<PlusOutlined />}
                  onClick={() => handleFormOpen('create')}
                  className="page-template-toolbar-primary-btn"
                >
                  {t('common', 'create')}
                </Button>
              )}
              {renderBatchActions && renderBatchActions(selectedRowKeys, selectedRows)}
            </Space>
          }
          loading={loading}
          rowSelection={
            enabled
              ? {
                  selectedRowKeys,
                  onChange: (keys, rows) => {
                    setSelectedRowKeys(keys);
                    setSelectedRows(rows);
                  },
                }
              : undefined
          }
          scroll={{ x: 'max-content' }}
          {...tableProps}
        />
      </Card>

      {(formFields || formSections) && (
        <CommonDrawer
          visible={formVisible}
          title={formTitleMap[formMode]}
          width="60%"
          onClose={handleFormCancel}
          onConfirm={formMode !== 'view' ? () => onFormSubmitHandler(actionRef) : undefined}
          confirmText={confirmTextMap[formMode]}
          showDefaultFooter={formMode !== 'view'}
        >
          <CommonForm
            ref={formRef}
            fields={formFields}
            sections={formSections}
            initialValues={formInitialValues}
            disabled={formMode === 'view'}
          />
        </CommonDrawer>
      )}
    </div>
  );
}

export default PageTemplate;
